package org.example.device.service;

import org.example.device.control.DeviceControlCommand;
import org.example.device.control.DeviceControlInterface;
import org.example.device.control.DeviceControlResult;
import org.example.device.registry.DeviceControllerRegistry;
import org.example.entity.Device;
import org.example.repository.DeviceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 真实设备控制服务
 * 统一管理真实设备的控制逻辑
 */
@Service
public class RealDeviceControlService {
    
    @Autowired
    private DeviceControllerRegistry controllerRegistry;
    
    // 协议注册中心，用于未来扩展
    // @Autowired
    // private DeviceProtocolRegistry protocolRegistry;
    
    @Autowired
    private DeviceRepository deviceRepository;
    
    /**
     * 执行设备控制命令
     */
    public DeviceControlResult executeDeviceCommand(Long deviceId, DeviceControlCommand command) {
        try {
            // 获取设备信息
            Device device = deviceRepository.findById(deviceId)
                .orElseThrow(() -> new RuntimeException("设备不存在"));
            
            // 获取设备类型
            String deviceType = getDeviceTypeFromDevice(device);
            
            // 获取对应的控制器
            DeviceControlInterface controller = controllerRegistry.getController(deviceType);
            if (controller == null) {
                return DeviceControlResult.failure("不支持的设备类型: " + deviceType, "UNSUPPORTED_DEVICE_TYPE");
            }
            
            // 执行控制命令
            return controller.executeCommand(command);
        } catch (Exception e) {
            return DeviceControlResult.failure("设备控制失败: " + e.getMessage(), "CONTROL_ERROR");
        }
    }
    
    /**
     * 获取设备状态
     */
    public Map<String, Object> getDeviceStatus(Long deviceId) {
        try {
            Device device = deviceRepository.findById(deviceId)
                .orElseThrow(() -> new RuntimeException("设备不存在"));
            
            String deviceType = getDeviceTypeFromDevice(device);
            DeviceControlInterface controller = controllerRegistry.getController(deviceType);
            
            if (controller != null) {
                return controller.getDeviceStatus(deviceId);
            } else {
                return Map.of("error", "不支持的设备类型: " + deviceType);
            }
        } catch (Exception e) {
            return Map.of("error", "获取设备状态失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查设备是否在线
     */
    public boolean isDeviceOnline(Long deviceId) {
        try {
            Device device = deviceRepository.findById(deviceId)
                .orElseThrow(() -> new RuntimeException("设备不存在"));
            
            String deviceType = getDeviceTypeFromDevice(device);
            DeviceControlInterface controller = controllerRegistry.getController(deviceType);
            
            if (controller != null) {
                return controller.isDeviceOnline(deviceId);
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 测试设备连接
     */
    public DeviceControlResult testDeviceConnection(Long deviceId) {
        try {
            Device device = deviceRepository.findById(deviceId)
                .orElseThrow(() -> new RuntimeException("设备不存在"));
            
            String deviceType = getDeviceTypeFromDevice(device);
            DeviceControlInterface controller = controllerRegistry.getController(deviceType);
            
            if (controller != null) {
                return controller.testConnection(deviceId);
            } else {
                return DeviceControlResult.failure("不支持的设备类型: " + deviceType, "UNSUPPORTED_DEVICE_TYPE");
            }
        } catch (Exception e) {
            return DeviceControlResult.failure("设备连接测试失败: " + e.getMessage(), "CONNECTION_TEST_ERROR");
        }
    }
    
    /**
     * 获取设备支持的指令
     */
    public java.util.List<String> getDeviceSupportedCommands(Long deviceId) {
        try {
            Device device = deviceRepository.findById(deviceId)
                .orElseThrow(() -> new RuntimeException("设备不存在"));
            
            String deviceType = getDeviceTypeFromDevice(device);
            DeviceControlInterface controller = controllerRegistry.getController(deviceType);
            
            if (controller != null) {
                return controller.getSupportedCommands(deviceId);
            } else {
                return java.util.Collections.emptyList();
            }
        } catch (Exception e) {
            return java.util.Collections.emptyList();
        }
    }
    
    /**
     * 获取设备属性
     */
    public Map<String, Object> getDeviceProperties(Long deviceId) {
        try {
            Device device = deviceRepository.findById(deviceId)
                .orElseThrow(() -> new RuntimeException("设备不存在"));
            
            String deviceType = getDeviceTypeFromDevice(device);
            DeviceControlInterface controller = controllerRegistry.getController(deviceType);
            
            if (controller != null) {
                return controller.getDeviceProperties(deviceId);
            } else {
                return Map.of("error", "不支持的设备类型: " + deviceType);
            }
        } catch (Exception e) {
            return Map.of("error", "获取设备属性失败: " + e.getMessage());
        }
    }
    
    /**
     * 设置设备属性
     */
    public DeviceControlResult setDeviceProperties(Long deviceId, Map<String, Object> properties) {
        try {
            Device device = deviceRepository.findById(deviceId)
                .orElseThrow(() -> new RuntimeException("设备不存在"));
            
            String deviceType = getDeviceTypeFromDevice(device);
            DeviceControlInterface controller = controllerRegistry.getController(deviceType);
            
            if (controller != null) {
                return controller.setDeviceProperties(deviceId, properties);
            } else {
                return DeviceControlResult.failure("不支持的设备类型: " + deviceType, "UNSUPPORTED_DEVICE_TYPE");
            }
        } catch (Exception e) {
            return DeviceControlResult.failure("设置设备属性失败: " + e.getMessage(), "SET_PROPERTIES_ERROR");
        }
    }
    
    /**
     * 从设备实体获取设备类型
     * 这里需要根据实际的设备类型映射逻辑来实现
     */
    private String getDeviceTypeFromDevice(Device device) {
        // 这里需要根据实际的业务逻辑来映射设备类型
        // 可以通过device.getDeviceTypeId()查询设备类型表，或者通过其他方式确定
        
        // 临时实现：根据设备名称或其他属性判断
        String deviceName = device.getName().toLowerCase();
        if (deviceName.contains("light") || deviceName.contains("灯")) {
            return "SMART_LIGHT";
        } else if (deviceName.contains("thermostat") || deviceName.contains("空调") || deviceName.contains("温控")) {
            return "SMART_THERMOSTAT";
        } else {
            // 默认返回通用设备类型
            return "GENERIC_DEVICE";
        }
    }
}
